package cc.md888.app.application.live;

import cc.md888.app.enums.AccountLiveStatusEnum;
import cc.md888.app.utils.RandomUserAgent;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.net.URI;

@Slf4j
@Component
public class FacebookAccountLiveChecker implements AccountLiveChecker {

    private final RestTemplate restTemplate = new RestTemplate();


    /**
     * 访问 {@link https://graph.facebook.com/61581024462693/picture?type=normal&redirect=false} 如返回302表示账号存活
     * @param uid facebook 账号id
     * @return
     */
    @Override
    public String check(String uid) {

        try{
            String checkUrl = String.format(
                    "https://graph.facebook.com/%s/picture?type=normal&redirect=false",
                    uid
            );
            log.info("{} check url: {}",uid,  checkUrl);
            RequestEntity<Void> request = RequestEntity.<Void>get(new URI(checkUrl))
                    .header("user-agent", RandomUserAgent.getRandomUserAgent())
//                    .header("accept-encoding", "gzip, deflate, br")
                    .header("accept-language", "zh,en;q=0.9,zh-CN;q=0.8")
                    .header("accept", "application/json, text/plain, */*")
                    .build();

            ResponseEntity<String> response = restTemplate.exchange(request, String.class);
            if(!response.getStatusCode().is2xxSuccessful()){
                return AccountLiveStatusEnum.UNKNOWN.name();
            }

            String body = response.getBody();
            log.info("{} check body: {}",uid,  body);

            JSONObject result = JSONObject.parseObject(body);
            JSONObject data = result.getJSONObject("data");
            //检查是否存活
            if(data.containsKey("width") && data.containsKey("height")){
                return AccountLiveStatusEnum.ACTIVE.name();
            }else{
                return AccountLiveStatusEnum.BAN.name();
            }
        }catch (Exception e){
            log.error("facebook account check error", e);
            return AccountLiveStatusEnum.UNKNOWN.name();
        }
    }


}
